import { PatchState, Transaction } from "@rivet/state";

export function createChainableState(config: {
  transaction: Transaction;
  state: PatchState;
}): PatchState {
  const { state, transaction } = config;
  let { doc } = transaction;
  return {
    ...state,
    applyInner: state.applyInner.bind(state),
    apply: state.apply.bind(state),
    applyTransaction: state.applyTransaction.bind(state),
    filterTransaction: state.filterTransaction,
    plugins: state.plugins,
    schema: state.schema,
    reconfigure: state.reconfigure.bind(state),
    toJSON: state.toJSON.bind(state),
    get doc() {
      return doc;
    },
    get tr() {
      doc = transaction.doc;
      return transaction;
    },
  };
}
